package com.jiali.backend.service.impl;

import com.jiali.backend.common.ResponseResult;
import com.jiali.backend.mapper.AppointmentOrderMapper;
import com.jiali.backend.model.AppointmentOrder;
import com.jiali.backend.model.ServiceItem;
import com.jiali.backend.model.Staff;
import com.jiali.backend.service.*;
import com.jiali.backend.Utils.UserServiceUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderStatisticsServiceImpl implements OrderStatisticsService {
    @Resource
    private AppointmentOrderMapper appointmentOrderMapper;
    @Resource
    private AppointmentOrderService appointmentOrderService;
    @Resource
    private ServiceItemService serviceItemService;
    @Resource
    private StaffService staffService;
    @Resource
    private UserServiceUtils userServiceUtils;



    @Override
    public ResponseResult<?> getOrderDistributionByService(HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 获取所有订单
        List<AppointmentOrder> orders = appointmentOrderService.list();

        // 按服务类型分组统计
        Map<Integer, Long> serviceCountMap = orders.stream()
                .collect(Collectors.groupingBy(AppointmentOrder::getServiceId, Collectors.counting()));

        // 获取服务项详情
        Map<Integer, ServiceItem> serviceMap = serviceItemService.listByIds(serviceCountMap.keySet())
                .stream()
                .collect(Collectors.toMap(ServiceItem::getId, item -> item));

        // 构建响应数据
        List<Map<String, Object>> result = serviceCountMap.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("serviceType", serviceMap.get(entry.getKey()).getServiceName());
                    item.put("count", entry.getValue());
                    return item;
                })
                .collect(Collectors.toList());

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult<?> getOrderDistributionByStatus(HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 获取所有订单并按状态分组统计
        Map<Integer, Long> statusCountMap = appointmentOrderService.list()
                .stream()
                .collect(Collectors.groupingBy(AppointmentOrder::getStatus, Collectors.counting()));

        // 构建响应数据
        List<Map<String, Object>> result = statusCountMap.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("status", getStatusName(entry.getKey()));
                    item.put("count", entry.getValue());
                    return item;
                })
                .collect(Collectors.toList());

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult<?> getOrderDistributionByTechnician(HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 获取所有订单并按技师分组统计
        Map<Integer, Long> technicianCountMap = appointmentOrderService.list()
                .stream()
                .filter(order -> order.getServiceTechnician() != null)
                .collect(Collectors.groupingBy(AppointmentOrder::getServiceTechnician, Collectors.counting()));

        // 获取技师详情
        Map<Integer, Staff> staffMap = staffService.listByIds(technicianCountMap.keySet())
                .stream()
                .collect(Collectors.toMap(Staff::getId, staff -> staff));

        // 构建响应数据
        List<Map<String, Object>> result = technicianCountMap.entrySet().stream()
                .map(entry -> {
                    Staff staff = staffMap.get(entry.getKey());
                    Map<String, Object> item = new HashMap<>();
                    item.put("technicianId", entry.getKey());
                    item.put("name", staff.getName());
                    item.put("position", getPositionName(staff.getPosition()));
                    item.put("completedOrders", entry.getValue());
                    return item;
                })
                .collect(Collectors.toList());

        return ResponseResult.success(result);
    }

    private String getStatusName(Integer status) {
        return switch (status) {
            case 0 -> "待确认";
            case 1 -> "维修中";
            case 2 -> "已完成";
            default -> "未知状态";
        };
    }

    private String getPositionName(Integer position) {
        return switch (position) {
            case 0 -> "初级技工";
            case 1 -> "中级技工";
            case 2 -> "高级技工";
            case 3 -> "专家";
            default -> "其他";
        };
    }
    @Override
    public ResponseResult<?> getMonthlyOrderTrend(HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 获取当前日期和12个月前的日期
        LocalDate endDate = LocalDate.now().plusDays(1);
        LocalDate startDate = endDate.minusMonths(11).withDayOfMonth(1); // 12个月前的第一天

        // 查询数据
        List<Map<String, Object>> monthlyData = appointmentOrderMapper.selectMonthlyOrderTrend(
                Date.from(startDate.atStartOfDay(ZoneId.systemDefault()).toInstant()),
                Date.from(endDate.atStartOfDay(ZoneId.systemDefault()).toInstant())
        );

        // 填充可能缺失的月份
        Map<String, Long> resultMap = new LinkedHashMap<>();
        for (int i = 0; i < 12; i++) {
            String monthKey = startDate.plusMonths(i).format(DateTimeFormatter.ofPattern("yyyy-MM"));
            resultMap.put(monthKey, 0L);
        }

        // 填充实际数据
        monthlyData.forEach(data -> {
            String month = (String) data.get("month");
            Long count = (Long) data.get("count");
            resultMap.put(month, count);
        });

        return ResponseResult.success(resultMap);
    }
}